package org.zuel.boot.demo.component;

import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zuel.boot.demo.model.DemoPerm;
import org.zuel.boot.demo.model.DemoRole;
import org.zuel.boot.demo.model.DemoUser;
import org.zuel.boot.demo.service.IAuthQueryService;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description: user用户授权基类
 * @Author: Athrun
 * @Date: 2019/4/7
 * @Version 1.0
 */

public abstract class UserAuthRealm extends AuthorizingRealm {
//通过继承realm，自定义！！！！用户的身份验证和权限加载逻辑。
    @Autowired
    private IAuthQueryService authQueryService;

    @Override
    //重写了方法，这个方法是调查用户拥有哪些权限和角色的。
    //这个方法实际非常重要，其是shiro的底层逻辑，
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        Object principal = getAvailablePrincipal(principals);
        if(!(principal instanceof DemoUser)) {
            return null;
        }
        DemoUser curUser = (DemoUser) principal;//从 PrincipalCollection 中提取当前用户对象（DemoUser）。
        List<DemoRole> roleList = authQueryService.queryRolesByUser(curUser.getId());//用id提取角色
        Set<String> roles = new HashSet<>();
        roleList.forEach(role -> {
            roles.add(role.getName());
        });//添加角色到列表
        List<DemoPerm> permList = authQueryService.queryPermsByUser(curUser.getId());//用id提取权限
        Set<String> perms = new HashSet<>();
        permList.forEach(perm -> {
            if(!StringUtils.isEmpty(perm.getPermEl())) {
            perms.add(perm.getPermEl());
        }});
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(perms);
        return info;
    }
}
